<template>
  <div class="login-container">
    <div class="login-card animate__animated animate__fadeInUp">
      <div class="logo">
        <img src="@/assets/imgs/logo.png" alt="Logo">
        <h1>NebulaNode</h1>
      </div>
      
      <el-form 
        :model="loginForm" 
        :rules="loginRules" 
        ref="loginFormRef" 
        @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          ></el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        
        <el-form-item prop="captcha" v-if="showCaptcha">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.captcha"
              placeholder="请输入验证码"
              prefix-icon="Key"
              style="width: 60%"
            ></el-input>
            <img 
              :src="captchaUrl" 
              class="captcha-img" 
              @click="refreshCaptcha"
              alt="验证码"
            >
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
          <el-link type="primary" @click="showForgetDialog" style="float: right">忘记密码?</el-link>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            :loading="loading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
        
        <el-form-item style="text-align: center">
          <el-link type="primary" @click="goToRegister">还没有账号? 立即注册</el-link>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 忘记密码对话框 -->
    <el-dialog v-model="forgetDialogVisible" title="找回密码" width="30%">
      <el-form :model="forgetForm" :rules="forgetRules" ref="forgetFormRef">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="forgetForm.email" placeholder="请输入注册邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="forgetDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleForget">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()

// 登录表单
const loginForm = reactive({
  id:'',
  username: '',
  password: '',
  captcha: '',
  remember: false
})

const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})

// 忘记密码表单
const forgetForm = reactive({
  email: ''
})

const forgetRules = reactive({
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
})

// 状态
const loading = ref(false)
const showCaptcha = ref(false)
const forgetDialogVisible = ref(false)
const captchaUrl = ref('')
const loginFormRef = ref(null)
const forgetFormRef = ref(null)

// 方法
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    // 调用后端API进行登录
    const res = await request.post('/api/login', {
      username: loginForm.username,
      password: loginForm.password
    })
    
    if (res.status === 'success') {
      // 存储用户信息到本地
      const userData = {
        id: res.data.user,
        name: res.data.user,
        role: res.data.role,
        token: res.data.token
      }
      
      localStorage.setItem('code_user', JSON.stringify(userData))
      
      // 如果选择了记住我，存储用户名
      if (loginForm.remember) {
        localStorage.setItem('remember_user', loginForm.username)
      } else {
        localStorage.removeItem('remember_user')
      }
      
      ElMessage.success('登录成功')
      router.push('/manager/home')
    } else {
      ElMessage.error(res.data.message || '登录失败')
      showCaptcha.value = true
      refreshCaptcha()
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

const refreshCaptcha = () => {
  captchaUrl.value = `https://picsum.photos/120/40?random=${Date.now()}`
}

const showForgetDialog = () => {
  forgetDialogVisible.value = true
}

const handleForget = async () => {
  try {
    await forgetFormRef.value.validate()
    
    // 模拟发送重置密码邮件
    ElMessage.success(`重置密码链接已发送至 ${forgetForm.email}`)
    forgetDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const goToRegister = () => {
  router.push('/register')
}

// 生命周期钩子
onMounted(() => {
  // 检查是否有记住的用户名
  const rememberUser = localStorage.getItem('remember_user')
  if (rememberUser) {
    loginForm.username = rememberUser
    loginForm.remember = true
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-card {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo img {
  width: 80px;
  height: 80px;
  margin-bottom: 10px;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  color: #2c3e50;
}

.captcha-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.captcha-img {
  width: 35%;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  margin-left: 10px;
}

@media (max-width: 768px) {
  .login-card {
    width: 90%;
    padding: 20px;
  }
}
</style>